/**
 * Created by zhourh on 2018/6/8.
 *
 * 编写一个函数，输入是一个无符号整数，返回其二进制表达式中数字位数为 ‘1’ 的个数（也被称为汉明重量）。
 *
 * 位运算
 */
public class Number0f1Bits {

    public static void main(String[] args) {
        System.out.println("11 weight = " + new Number0f1Bits().hammingWeight(11));
        System.out.println("128 weight = " + new Number0f1Bits().hammingWeight(128));
    }

    public int hammingWeight(int n) {
        int mask = 0x0001;
        int weight = 0;
        while (mask != 0) {
            weight += ((n & mask) != 0 ? 1 : 0);
            mask <<= 1;
        }

        return weight;
    }
}
